package com.sys.controller;

import com.aliyun.oss.OSSClient;
import com.baomidou.mybatisplus.extension.api.R;
import com.sys.common.constant.Constant;
import com.sys.common.util.ResponseDateUtil;
import com.sys.common.util.ResultBuilder;
import com.sys.utils.ConstantPropertiesUtil;
import org.apache.commons.lang.StringUtils;
import org.joda.time.DateTime;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

/**
 * @author Eric Fang
 * @version 1.0
 * @date 2022/3/28 12:22
 */
@RestController
@RequestMapping("/hrm/oss")
public class FileUploadController {

    @PostMapping("uploadFile")
    public ResponseDateUtil uploadTeacherImg(@RequestParam("file") MultipartFile file,
                                             @RequestParam(value = "host", required = false) String host) {
        try {
            String filename = file.getOriginalFilename();
            String uuid = UUID.randomUUID().toString();
            filename = uuid + filename;
            //获取当前时间
            String filepath = new DateTime().toString("yyyy/MM/dd");
            //拼接文件完整名称
            if (StringUtils.isEmpty(host)) {
                filename = filepath + "/"+ 123 + "/" + filename  ;
            } else {
                filename = filepath + "/" + host + "/" + filename;
            }
            InputStream in = file.getInputStream();

            // 创建OSSClient实例。
            OSSClient ossClient = new OSSClient(ConstantPropertiesUtil.ENDPOINT, ConstantPropertiesUtil.KEYID, ConstantPropertiesUtil.KEYSECRET);
            ossClient.putObject(ConstantPropertiesUtil.BUCKEYNAME, filename, in);
            // 关闭OSSClient。
            ossClient.shutdown();
            //https://eric123.oss-cn-shanghai.aliyuncs.com/0406_1.jpg
            String path = "http://" + ConstantPropertiesUtil.BUCKEYNAME + "." + ConstantPropertiesUtil.ENDPOINT + "/" + filename;
            return ResultBuilder.success(path);
        } catch (Exception e) {
            return ResultBuilder.errorInfo(Constant.ADDFAILED);
        }
    }
}
